#include <bits/stdc++.h>
#ifndef DEBUG
#define debug
#endif
using namespace std;
using i64 = int64_t;

int main() {
  cin.tie(0)->sync_with_stdio(0);
  int T;
  cin >> T;
  while (T --) {
    int n;
    cin >> n;
    vector<i64> a(n), b(n);
    for (auto &x : a) cin >> x;
    for (auto &x : b) cin >> x;
    i64 lo = 0, hi = 1e12;
    while (lo <= hi) {
      i64 mid = (lo + hi) / 2;
      if ([&](i64 x) {
        i64 coin = 0;
        deque<pair<i64, i64>> q; // 价格高->低，可以以这个价格购买的钱
        for (int i = 0; i < n; i ++) {
          i64 price = a[i], cnt = b[i];
          while (!q.empty() && q.back().first <= price) {
            cnt += q.back().second;
            q.pop_back();
          }
          q.emplace_back(price, cnt);
          while (!q.empty() && coin + q.front().first * q.front().second < x) {
            coin += q.front().first * q.front().second;
            q.pop_front();
          }
          if (q.empty()) return false;
          i64 need = x - coin;
          i64 buy = (need - 1) / q.front().first + 1;
          coin += buy * q.front().first;
          q.front().second -= buy;
          if (q.front().second == 0) q.pop_front();
          coin -= x;
        }
        return true;
      }(mid)) lo = mid + 1;
      else hi = mid - 1;
    }
    cout << hi << endl;
  }
}